﻿using System.ComponentModel;
using System.Windows.Forms;
using Map_Creator.MapInfo;

namespace Map_Creator.MainForm.Controls.MenuStrips
{
    public partial class LayerMenuStrip : ContextMenuStrip
    {
        public LayerMenuStrip()
        {
            InitializeComponent();
        }

        public LayerMenuStrip(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        private void MoveUpOnClick(object sender, System.EventArgs e)
        {
            var node = MapTreeView.Instance.SelectedNode as ExtendedTreeNode;
            if (node == null) return;

            var layer = node.Obj as Layer;

            var tree = node.TreeView;
            var parent = node.Parent;

            if (layer.Level > 0)
            {
                tree.BeginUpdate();

                node.Remove();
                var prevLayer = layer.AssociatedMap[layer.Level - 1];
                parent.Nodes.Insert(layer.Level - 1, node);
                layer.Level--;
                prevLayer.Level++;
                tree.SelectedNode = node;

                tree.EndUpdate();

                // this will force update on everything that depends on layers
                layer.AssociatedMap.CurrentLayer = null;
                layer.AssociatedMap.CurrentLayer = layer;
            }
        }

        private void MoveDownOnClick(object sender, System.EventArgs e)
        {
            var node = MapTreeView.Instance.SelectedNode as ExtendedTreeNode;
            if (node == null) return;

            var layer = node.Obj as Layer;

            var tree = node.TreeView;
            var parent = node.Parent;

            if (layer.Level < layer.AssociatedMap.Levels - 1)
            {
                tree.BeginUpdate();

                node.Remove();
                var nextLayer = layer.AssociatedMap[layer.Level + 1];
                parent.Nodes.Insert(layer.Level + 1, node);
                layer.Level++;
                nextLayer.Level--;
                tree.SelectedNode = node;

                tree.EndUpdate();

                // this will force update on everything that depends on layers
                layer.AssociatedMap.CurrentLayer = null;
                layer.AssociatedMap.CurrentLayer = layer;
            }
        }

        private void OnOpened(object sender, System.EventArgs e)
        {
            var node = MapTreeView.Instance.SelectedNode as ExtendedTreeNode;
            if (node == null) return;

            var layer = node.Obj as Layer;

            MoveDownMenuItem.Enabled =
                layer.Level < layer.AssociatedMap.Levels - 1;

            MoveUpMenuItem.Enabled =
                layer.Level > 0;
        }
    }
}
